package crontab

import (
	"github.com/spf13/cast"
	global2 "longmen/server/config/global"
	"longmen/server/pkg/db/mysql/models/models_live"
	"longmen/server/pkg/db/redis/cache"
	"strings"
)

func SyncLives() {
	// log.Println("begin sync lives")
	// 所有正在直播中的
	var lives []models_live.Live
	err := global2.Live().Model(&models_live.Live{}).Where("status=1").Find(&lives).Error
	if err != nil {
		global2.Log.Error("Sync models_live error : ", err)
	}
	var strSql strings.Builder
	// 将redis里面的热度同步到表
	for _, v := range lives {
		// 读取redis 直播中的统计数据
		cacheKey := cache.GenStatsCacheKey(v.Anchorid)
		cache, err := global2.GetRds().HGetAll(cacheKey).Result()
		if err != nil {
			global2.Log.Error("Sync db_live error in redis : ", err)
		}
		if cache["hot"] != "" && cast.ToInt(cache["hot"]) != v.Hot {
			strSql = assembleLiveSql(strSql, v.Anchorid, cache["hot"])
		}
	}
	commitSyncLives(strSql)
}

func assembleLiveSql(strSql strings.Builder, anchorId int, hot string) strings.Builder {
	strSql.WriteString("(" + cast.ToString(anchorId))
	strSql.WriteString(",'" + hot + "'),")

	return strSql
}

func commitSyncLives(strSql strings.Builder) {
	if strSql.Len() > 0 {
		session := global2.Live().Begin()
		/*defer func() {
			if r := recover(); r != nil {
				session.Rollback()
			}
		}()*/
		sql := "insert into syncLives_time (anchor_id,hot) values" + strings.TrimRight(strSql.String(), ",")
		if err := session.Exec("CREATE TEMPORARY TABLE syncLives_time (anchor_id bigint,hot varchar(50))").Error; err != nil {
			session.Rollback()
		}
		if err := session.Exec(sql).Error; err != nil {
			session.Rollback()
		}
		if err := session.Exec("update db_live t1,syncLives_time t2 set t1.hot=t2.hot  where t1.anchorid=t2.anchor_id").Error; err != nil {
			session.Rollback()
		}
		if err := session.Exec("DROP TEMPORARY TABLE IF EXISTS syncLives_time").Error; err != nil {
			session.Rollback()
		}
		if err := session.Commit().Error; err != nil {
			session.Rollback()
		}
	}
}
